package com.zhilianbao.leyaogo.utils;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bql.convenientlog.CLog;
import com.bql.fragmentation.ControllerActivity;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.model.response.category.SkuEntity;
import com.zhilianbao.leyaogo.model.response.category.SkuMapEntity;
import com.zhilianbao.leyaogo.view.widgets.GoodsSpecLayout;
import com.zhilianbao.leyaogo.view.widgets.MoneyTextView;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 商品规格popWindow工具类
 * Created by gyt on 2016/11/29
 */
public class GoodsSpecPopUtils implements View.OnClickListener {

    @BindView(R.id.rl_outside)
    RelativeLayout mRlOutside;
    @BindView(R.id.iv_goods_icon)
    ImageView      mIvGoodsIcon;
    @BindView(R.id.rl_goods_pic)
    RelativeLayout mRlGoodsPic;
    @BindView(R.id.mtv_price)
    MoneyTextView  mMtvPrice;
    @BindView(R.id.rl_close)
    RelativeLayout mRlClose;
    @BindView(R.id.ll_goods_info)
    RelativeLayout mLlGoodsInfo;
    @BindView(R.id.view_divider)
    View           mViewDivider;
    @BindView(R.id.ll_goods_spec_layout)
    LinearLayout   mLlGoodsSpecLayout;
    @BindView(R.id.tv_confirm)
    TextView       mTvConfirm;

    private String                mPicUrl;
    private Context               mContext;
    private View                  mRootView;
    private List<SkuEntity>       mSkuEntities;
    private List<SkuMapEntity>    mSkuMapEntities;
    private int                   mGoodsSkuId;
    private TextView              mTvSpecName;
    private Map<Integer, Integer> specMap;
    private PopupWindow           popupWindow;
    private OnPopClickListener    mListener;
    private int                   mSelectedSkuId;
    private int mStatusCode;


    private GoodsSpecPopUtils() {
    }

    public static GoodsSpecPopUtils getInstance() {
        GoodsSpecPopUtils utils = new GoodsSpecPopUtils();
        return utils;
    }
    //
    //    public void show(Context context, View rootView, Drawable drawable, GoodsDetails goodsDetails, OnPopClickListener listener) {
    //        show(context, rootView, drawable, goodsDetails.getGoodsSkuId(), goodsDetails.getSelectedSkuId(), goodsDetails.getSku(), goodsDetails.getSkuMap(), listener);
    //    }
    //
    //    public void show(Context context, View rootView, Drawable drawable, GoodsInfo goodsInfo, OnPopClickListener listener) {
    //        show(context, rootView, drawable, goodsInfo.getGoodsSkuId(), goodsInfo.getSelectedSkuId(), goodsInfo.getSku(), goodsInfo.getSkuMap(), listener);
    //    }

    /**
     * 弹出选择商品规格的pop，适用于首页，搜索，分类页面等。
     *
     * @param context
     * @param rootView       如果是fragment中使用getView获得
     * @param statusCode      状态 0 下架 1 上架 ,只在商品详情页面用到，只有该页面返回这个字段，其他页面可直接传入1
     * @param picUrl         popwindow中所显示的图片资源，
     * @param skuEntities    sku类型商品的SkuEntity集合，请把自己javaBean的SkuEntity替换成这个{@link SkuEntity}
     * @param skuMapEntities sku类型商品的SkuMapEntity集合，请把自己javaBean的SkuMapEntity替换成这个{@link SkuMapEntity}
     */
    public void show(Context context, View rootView, int statusCode, String picUrl, int goodsSkuId, int selectedSkuId, List<SkuEntity> skuEntities, List<SkuMapEntity> skuMapEntities, OnPopClickListener listener) {
        mContext = context;
        mGoodsSkuId = goodsSkuId;
        mSelectedSkuId = selectedSkuId;
        mRootView = rootView;
        mListener = listener;
        mPicUrl = picUrl;
        mSkuEntities = skuEntities;
        mSkuMapEntities = skuMapEntities;
        mStatusCode = statusCode;

        // 用map集合储存规格在skuMap的index和ItemId
        specMap = new HashMap(skuMapEntities.size());
        initPopWindow();

        if (popupWindow != null && mRootView != null) {
            popupWindow.showAtLocation(mRootView, Gravity.BOTTOM, 0, 0);
        }
    }


    private void initPopWindow() {
        popupWindow = new PopupWindow(mContext);
        popupWindow = new PopupWindow(initContentView(), LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        popupWindow.setFocusable(true);
        popupWindow.setAnimationStyle(R.style.PopAnimation);

        WindowManager.LayoutParams wLp = ((ControllerActivity) mContext).getWindow().getAttributes();
        wLp.alpha = 0.5f;
        ((ControllerActivity) mContext).getWindow().setAttributes(wLp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                wLp.alpha = 1.0f;
                ((ControllerActivity) mContext).getWindow().setAttributes(wLp);
            }
        });
    }

    private View initContentView() {
        View contentView = View.inflate(mContext, R.layout.view_pop_goods_spec, null);
        ButterKnife.bind(this, contentView);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        ImageUtils.loadRoundPic(Utils.returnUrlShow(mPicUrl), mIvGoodsIcon);

        setPopState();
        for (int i = 0; i < mSkuMapEntities.size(); i++) {
            List<SkuMapEntity.GoodsSkuMapItemEntity> goodsSkuMapItemList = mSkuMapEntities.get(i).getGoodsSkuMapItemResponse();
            // 解析xml布局添加到容器中
            View specView = View.inflate(mContext, R.layout.view_pop_goods_spec_layout, null);
            mTvSpecName = (TextView) specView.findViewById(R.id.tv_spec_name);
            GoodsSpecLayout gslSpecLayout = (GoodsSpecLayout) specView.findViewById(R.id.gsl_goods_spec);
            mTvSpecName.setText(mSkuMapEntities.get(i).getSkuName());
            gslSpecLayout.setItemData(goodsSkuMapItemList);

            mLlGoodsSpecLayout.addView(specView, lp);
            int finalI = i;
            gslSpecLayout.setOnSpecItemClickListener(new GoodsSpecLayout.OnSpecItemClickListener() {
                @Override
                public void onSpecItemClick(View v, int currentPosition) {
                    int itemId = goodsSkuMapItemList.get(currentPosition).getItemId();
                    specMap.put(finalI, itemId);
                    isBingo();
                }
            });
        }
        if (mStatusCode == 0) {
            mTvConfirm.setClickable(false);
            mTvConfirm.setText(mContext.getResources().getString(R.string.goods_off_the_shelf));
            mTvConfirm.setBackgroundColor(mContext.getResources().getColor(R.color.color_enable_false));
        } else {
            mTvConfirm.setClickable(true);
            mTvConfirm.setOnClickListener(this);
        }
        mRlOutside.setOnClickListener(this);
        mRlClose.setOnClickListener(this);
        return contentView;
    }

    /**
     * 设置默认选中状态或者之前的选中状态
     */
    private void setPopState() {
        CLog.i("mgoodsSkuId = " + mGoodsSkuId);
        // 如果goodsSkuId不为0，则遍历找到默认选中的sku规格

        //mSelectedSkuId字段代表之前选中的规格对应的goodsSkuId,
        if (mSelectedSkuId != 0) {
            mGoodsSkuId = mSelectedSkuId;
        }
        String itemIds = "";
        double minPrice = Double.MAX_VALUE;
        for (SkuEntity skuEntity : mSkuEntities) {
            // 如果skuId不为0，则显示该skuId对应规格的价格，否则遍历显示最小价格

            if (mGoodsSkuId != 0) {
                if (skuEntity.getGoodsSkuId() == mGoodsSkuId) {
                    itemIds = skuEntity.getItemIds();
                    CLog.i("goodsSelcetedPrice = " + skuEntity.getPrice());

                    mMtvPrice.setAmount(skuEntity.getPrice());
                    break;
                }
            }
            CLog.i("skuPrice ==================" + skuEntity.getPrice());
            if (skuEntity.getPrice() < minPrice) {
                minPrice = skuEntity.getPrice();
            }
        }

        if (mGoodsSkuId == 0) {
            CLog.i("goodsSelcetedPrice = " + minPrice);
            mMtvPrice.setAmount(minPrice);
        }


        // 上次选中的规则或者默认选中的规则对应的sku的itemIds,在skuMapItem中遍历，找到对应的被选中的item
        String[] itemIdArray = itemIds.split("-");
        List<String> itemIdList = Arrays.asList(itemIdArray);

        for (int i = 0; i < mSkuMapEntities.size(); i++) {
            SkuMapEntity skuMapEntity = mSkuMapEntities.get(i);
            List<SkuMapEntity.GoodsSkuMapItemEntity> goodsSkuMapItemLists = skuMapEntity.getGoodsSkuMapItemResponse();
            for (SkuMapEntity.GoodsSkuMapItemEntity goodsSkuMapItem : goodsSkuMapItemLists) {
                if (itemIdList.contains(String.valueOf(goodsSkuMapItem.getItemId()))) {
                    CLog.i("goodsSkuMapItemIds = " + goodsSkuMapItem.getItemId());
                    goodsSkuMapItem.setSelected(true);
                    specMap.put(i, goodsSkuMapItem.getItemId());
                }
            }
        }
        isBingo();
        CLog.i("selected_item_id = " + specMap.toString() + "  mapsize = " + specMap.size());
    }


    public void isBingo() {

        // 下面进行遍历判断，用户选中的规格
        // 从Sku集合中遍历，拿其中的itemIds用“-”分割成数组转换成集合再遍历选中的规格对应的itemId，
        // 判断是否contain，如果有一个不包括，说明不是该sku，接着下一个。
        if (specMap.size() == mSkuMapEntities.size()) {// 如果用户把多个规格都选中了
            for (int j = 0; j < mSkuEntities.size(); j++) {
                SkuEntity skuEntity = mSkuEntities.get(j);
                String itemIds = skuEntity.getItemIds();
                String[] itemIdArray = itemIds.split("-");
                List<String> itemIdLists = Arrays.asList(itemIdArray);
                boolean bingo = true;
                // 从map中得到value值集合即用户选择的规格itemId
                Collection<Integer> specs = specMap.values();
                for (Integer itemId : specs) {
                    bingo &= itemIdLists.contains(String.valueOf(itemId));
                }

                if (bingo) {
                    mGoodsSkuId = skuEntity.getGoodsSkuId();
                    mMtvPrice.setAmount(skuEntity.getPrice());
                    // 当完整的规格被选中后
                    if (mListener != null) {
                        mListener.onSpecSelect(skuEntity);
                    }
                    CLog.i("spec = " + skuEntity.getGoodsSkuName());
                    break;
                }
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_outside:
            case R.id.rl_close:
                if (popupWindow != null)
                    popupWindow.dismiss();
                break;
            case R.id.tv_confirm:
                if (mGoodsSkuId == 0) {//没有选择商品规则，则toast提醒
                    XToastUtils.showShortToast(R.string.msg_select_goods_spec);
                } else {
                    if (popupWindow != null && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    }
                    // 点击pop中加入购物车按钮，则把goodsSkuId返回出去
                    if (mListener != null && !popupWindow.isShowing()) {
                        mListener.onAddToCart(v, mGoodsSkuId);
                    }
                }
                break;
        }
    }

    public interface OnPopClickListener {
        // 当点击添加到购物车
        void onAddToCart(View v, int goodsSkuId);

        // 当完整的选中商品的规格后,在此处要设置selectedSkuId = skuEntity.getGoodsSkuId();
        void onSpecSelect(SkuEntity skuEntity);
    }


}
